package com.xii.educenter.controller;


import com.xii.commonutils.JwtUtils;
import com.xii.commonutils.R;
import com.xii.educenter.entity.UcenterMember;
import com.xii.educenter.entity.vo.RegisterVo;
import com.xii.educenter.service.UcenterMemberService;
import com.xii.servicebase.exceptionhandler.XiiException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author xhjava
 * @since 2022-03-17
 */
@RestController
@RequestMapping("/educenter/ucentermember")
//@CrossOrigin
public class UcenterMemberController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    /**
     * 会员登录
     * @param ucenterMember
     * @return
     */
    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public R login(@RequestBody UcenterMember ucenterMember) {
        String token = ucenterMemberService.login(ucenterMember);
        return R.ok().data("token", token);
    }

    /**
     * 会员注册
     * @param registerVo
     * @return
     */
    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public R register(@RequestBody RegisterVo registerVo){
        ucenterMemberService.register(registerVo);
        return R.ok();
    }


    /**
     * 根据token获取登录信息
     * @param request
     * @return
     */
    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("auth/getLoginInfo")
    public R getLoginInfo(HttpServletRequest request){
        try {
            //JWT获取token中的用户信息 传给userInfo
            String memberId = JwtUtils.getMemberIdByJwtToken(request);
            UcenterMember member = ucenterMemberService.getById(memberId);
            return R.ok().data("userInfo", member);
        }catch (Exception e){
            e.printStackTrace();
            throw new XiiException(20001,"error");
        }
    }



    //根据token字符串获取用户信息    注意 返回的是commons中的UcenterMember
    @GetMapping("getInfoUc/{id}")
    public com.xii.commonutils.ordervo.UcenterMember getInfo(@PathVariable String id) {
        //根据用户id获取用户信息
        UcenterMember ucenterMember = ucenterMemberService.getById(id);
        com.xii.commonutils.ordervo.UcenterMember memeber = new com.xii.commonutils.ordervo.UcenterMember();
        BeanUtils.copyProperties(ucenterMember,memeber);
        return memeber;
    }

    /**
     * 远程调用查询会员人数
     * @param day 指定天数
     * @return
     */
    @GetMapping("countRegister/{day}")
    public R getMemberCount(@PathVariable String day){
        Integer count = ucenterMemberService.countRegisterDay(day);
        return R.ok().data("countRegister",count);
    }
}

